package com.yt.lxh.common.service;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.yt.lxh.common.exception.ServiceException;
import com.yt.lxh.common.exception.TokenException;
import com.yt.lxh.common.result.ResultCodeEnum;
import com.yt.lxh.common.utils.AuthContextUtil;
import com.yt.lxh.constant.RedisEnum;
import com.yt.lxh.model.acl.Admin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class CheckLogin {

    @Autowired
    private CacheService cacheService;

    /**
     * 解析缓存在redis中的用户信息
     *
     * @param adminToken 管理员登录Token
     * @return Admin 管理员信息
     */
    public Admin checkAdmin(String adminToken) {
        String key = RedisEnum.ADMIN.getMessage() + adminToken;
        String adminJson = cacheService.get(key);
        if (StrUtil.isBlank(adminJson)) {
            throw new ServiceException(ResultCodeEnum.NEED_LOGIN);
        }
        return JSON.parseObject(adminJson, Admin.class);
    }

    // 判断是否登录，返回管理员信息
    public Admin checkAdminLogin() {
        Admin admin = AuthContextUtil.get();
        if (ObjectUtil.isEmpty(admin)) {
            throw new TokenException(ResultCodeEnum.NEED_LOGIN);
        }
        return admin;
    }
}
